package com.kitkat.message.handler;

import java.util.HashMap;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.kitkat.message.ActiveAccountMessage;
import com.kitkat.message.Message;

@Component
public class ActiveAccountMessageSender extends AbstractMessageSender{
	@Autowired
	private JavaMailSender mailSender;
	@Autowired
	private VelocityEngine velocityEngine;
	
	@Override
	public boolean supports(Message message) {
		return message instanceof ActiveAccountMessage;
	}
	@Override
	public void doWithMessage(Message message) {
		ActiveAccountMessage temp = (ActiveAccountMessage)message;
		MimeMessage mimeMessage = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
		try {
			helper.setFrom("taokeba@126.com");
			helper.setTo(temp.getTo());
			helper.setSubject("KITKAT——账号激活");
			Map<String,Object> hm = new HashMap<String,Object>();
			hm.put("href", temp.getHref());
			String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "activeAccount.vm", "utf-8", hm);
			helper.setText(text, true);
			helper.setPriority(1);
			mimeMessage.setContent(text, "text/html; charset=utf-8");
			mimeMessage.saveChanges();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		mailSender.send(mimeMessage);
	}
	
	
}
